package cn.tk.service.mr.impl;

import cn.tk.cache.mr.EntityBuf;
import cn.tk.cache.mr.VariableBuf;
import cn.tk.model.pojo.mr.flow.FuncNodeDTO;
import cn.tk.model.pojo.mr.flow.FuncNodeParameter;
import cn.tk.service.mr.FuncNodeService;
import cn.tk.utils.EmptyUtil;
import cn.tk.utils.JpaMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by denglw on 2021/8/3.<br/>
 * Desc: 函数节点 服务实现层
 */
@Service
public class FuncNodeServiceImpl implements FuncNodeService {

    @Autowired
    private JpaMapper jpaMapper;

    @Override
    public FuncNodeDTO getFuncNode(Long nodeId) {
        if (EmptyUtil.nullOrZero(nodeId)) {
            return null;
        }
        FuncNodeDTO dto = this.baseFuncNode(nodeId);
        if (dto == null) {
            return null;
        }
        List<FuncNodeParameter> parameters = this.funcNodeParameters(nodeId);
        dto.setFuncNodeParameters(parameters);
        return dto;
    }

    private FuncNodeDTO baseFuncNode(long nodeId) {
        String sql = "select a.id nodeId, b.id funcId, b.url funcUrl\n" +
                "from mr_flow_func_node a, mr_func b \n" +
                "where a.func_id=b.id and a.id=:nodeId and b.deleted=0 and b.disabled=0";
        Map<String, Object> params = new HashMap<>(4);
        params.put("nodeId", nodeId);
        Class<?>[] clazzes = new Class[] {Long.class, Long.class, String.class};
        return jpaMapper.queryOne(sql, params, FuncNodeDTO.class, clazzes).orElse(null);
    }

    private List<FuncNodeParameter> funcNodeParameters(long nodeId) {
        String sql = "select a.flow_node_id nodeId, a.name, a.param_type paramType, a.type, a.ref_id variableId, null entityId \n" +
                "from mr_flow_func_parameter a where flow_node_id=:nodeId and type=1\n" +
                "union all\n" +
                "select a.flow_node_id nodeId, a.name, a.param_type paramType, a.type, null variableId, a.ref_id entityId \n" +
                "from mr_flow_func_parameter a where flow_node_id=:nodeId and type=2";
        Map<String, Object> params = new HashMap<>(4);
        params.put("nodeId", nodeId);
        Class<?>[] clazzes = new Class[]{Long.class, String.class, Integer.class, Integer.class, Long.class, Long.class};
        List<FuncNodeParameter> queryList = jpaMapper.queryList(sql, params, FuncNodeParameter.class, clazzes);
        if (EmptyUtil.emptyColl(queryList)) {
            return queryList;
        }
        VariableBuf variableBuf = VariableBuf.getInstance();
        EntityBuf entityBuf = EntityBuf.getInstance();
        for (FuncNodeParameter i : queryList) {
            i.setEntityCode(entityBuf.getCode(i.getEntityId()));
            i.setVariableEnName(variableBuf.getEnName(i.getVariableId()));
        }
        return queryList;
    }

}
